import { Modal, Form, Input, Space, Button, InputNumber, message, DatePicker, Radio, Row, Col, Select, UploadFile } from 'antd';
const { TextArea } = Input;
const { RangePicker } = DatePicker;
import dayjs from 'dayjs';
import { useIntl } from "umi";
import React, { useState, useEffect, useRef } from 'react';
import { OPERATE_ADD, OPERATE_EDIT, SELECT_LABEL, SELECT_VALUE, RANGE_PICKER_FORMAT } from '../../../constants';
import { createCompetition, updateCompetition } from '@/services/competition';
import { queryCompQuesRoughInfoList } from '@/services/competitionQuestion';
import { set } from 'lodash';
const CompetitionOperatePanel = ({ operateType, record, closePanel }) => {
    const intl = useIntl();
    const [form] = Form.useForm(operateType === OPERATE_ADD ? { statusFlag: 'CREATED', roundCount: 1, roundDuration: 30 } : record);
    const [open, setOpen] = useState(true);
    const [confirmLoading, setConfirmLoading] = useState(false);
    const [selectLoading, setSelectLoading] = useState(true);
    //时间选择器--start
    const [competitionTime, setCompetitionTime] = useState(operateType === OPERATE_ADD ? [dayjs(), dayjs().add(1, 'day')] : [dayjs(record.startTime), dayjs(record.endTime)])
    const [registrationTime, setRegistrationTime] = useState(operateType === OPERATE_ADD ? [dayjs(), dayjs().add(1, 'day')] : [dayjs(record.registrationStartTime), dayjs(record.registrationEndTime)])
    //时间选择器--end
    const [compQuesSelectData,setCompQuesSelectData] = useState([])
    const handleOk = async (data) => {
        setConfirmLoading(true)
        //检查时间
        if (competitionTime[0] && competitionTime[1] && registrationTime[0] && registrationTime[1]) {
            data.startTime = dayjs(competitionTime[0]).format(RANGE_PICKER_FORMAT);
            data.endTime = dayjs(competitionTime[1]).format(RANGE_PICKER_FORMAT);
            data.registrationStartTime = dayjs(registrationTime[0]).format(RANGE_PICKER_FORMAT);
            data.registrationEndTime = dayjs(registrationTime[1]).format(RANGE_PICKER_FORMAT);
            if (operateType === OPERATE_ADD) {
                await createCompetition(data).then(res => {
                    if (res.success) {
                        message.success(res.msg)
                        setConfirmLoading(false)
                        handleCancel()
                    }
                })
            }else{
                data.unCode = record.unCode;
                await updateCompetition(data).then(res => {
                    if (res.success) {
                        message.success(res.msg)
                        setConfirmLoading(false)
                        handleCancel()
                    }
                })
            }
        } else {
            setConfirmLoading(false)
            message.error('请检查比赛周期时间或报名周期时间是否已填写')
        }

    }
    const handleCancel = () => {
        setOpen(false);
    };
    const competitionStatus = [
        { name: '已创建', unCode: 'CREATED' },
        { name: '初始化中', unCode: 'INITIALIZING' },
        { name: '初始化失败', unCode: 'INITIALIZATION_FAILED' },
        { name: '已初始化', unCode: 'INITIALIZED' },
        { name: '即将比赛', unCode: 'READY_FOR_COMP' },
        { name: '比赛中', unCode: 'IN_THE_COMP' },
        { name: '比赛结束', unCode: 'END_THE_COMP' },
        { name: '比赛暂停', unCode: 'PAUSE' },
    ];
    const initCompQuesSelectData = async()=>{
        await queryCompQuesRoughInfoList().then(res => {
                    if (res.success) {
                        setCompQuesSelectData(res.data)
                        setSelectLoading(false)
                    }
                }).catch(err => {
                    setSelectLoading(false)
                })
    }
    useEffect(() => {
        initCompQuesSelectData()
    }, [])
    return (
        <>
            <Modal
                title={operateType === OPERATE_ADD ? "新增赛事" : "编辑赛事"}
                open={open}
                destroyOnClose={true}
                onCancel={handleCancel}
                afterClose={closePanel}
                centered={true}
                footer={false}
            >
                <Form
                    name={form}
                    style={{
                        maxWidth: 600,
                    }}
                    onFinish={handleOk}
                    labelCol={{ span: 7 }}
                    wrapperCol={{ span: 17 }}
                    initialValues={form}
                    autoComplete="on"
                >
                    <Form.Item
                        label="赛事名称"
                        name="name"
                        rules={[
                            {
                                required: true,
                                message: "请输入赛事名称",
                            },
                        ]}
                    >
                        <Input placeholder="请输入赛事名称" />
                    </Form.Item>
                    {operateType === OPERATE_EDIT && <Form.Item
                        label="赛事状态"
                        name="statusFlag"
                        rules={[
                            {
                                required: true,
                                message: "请选择赛事状态",
                            },
                        ]}
                    >
                        <Select
                            fieldNames={{ label: SELECT_LABEL, value: SELECT_VALUE }}
                            showSearch
                            placeholder="选择状态"
                            filterOption={(input, option) =>
                                (option?.name ?? '').toLowerCase().includes(input.toLowerCase())
                            }
                            options={competitionStatus}
                        />
                    </Form.Item>}
                    <Form.Item
                        label="赛题文件"
                        name="competitionQuestionUnCode"
                        rules={[
                            {
                                required: true,
                                message: "请选择赛题文件",
                            },
                        ]}
                    >
                        <Select
                            fieldNames={{ label: SELECT_LABEL, value: SELECT_VALUE }}
                            showSearch
                            placeholder="搜索并选择赛题文件"
                            filterOption={(input, option) =>
                                (option?.name ?? '').toLowerCase().includes(input.toLowerCase())
                            }
                            options={compQuesSelectData}
                        />
                    </Form.Item>
                    <Form.Item
                        label="回合数"
                        name="roundCount"
                        rules={[
                            {
                                required: true,
                                message: "请输入回合数",
                            },
                        ]}
                    >
                        <InputNumber min={1} max={10} />
                    </Form.Item>
                    <Form.Item
                        label="每回合时长(分钟)"
                        name="roundDuration"
                        rules={[
                            {
                                required: true,
                                message: "请输入每回合时长，单位为分钟",
                            },
                        ]}
                    >
                        <InputNumber min={1} max={60} />
                    </Form.Item>
                    <Form.Item
                        label="初始总分"
                        name="initialTotalScore"
                        rules={[
                            {
                                required: true,
                                message: "请输入每支队伍初始总分",
                            },
                        ]}
                    >
                        <InputNumber min={1} max={999999999}/>
                    </Form.Item>
                    <Form.Item
                        label="每次攻击得分"
                        name="scorePerAttack"
                        rules={[
                            {
                                required: true,
                                message: "请输入每次攻击得分",
                            },
                        ]}
                    >
                        <InputNumber min={0} max={99999999}/>
                    </Form.Item>
                    <Form.Item
                        label="赛事比赛周期"
                        name="competitionTime"
                        valuePropName='competitionTime'
                        getValueProps={value => ({ value:competitionTime || value })}
                        getValueFromEvent={(_, value) => {
                            setCompetitionTime([dayjs(value[0]), dayjs(value[1])]);
                            return value;
                        }}
                    >
                        <RangePicker showTime />
                    </Form.Item>
                    <Form.Item
                        label="赛事报名周期"
                        name="registrationTime"
                        valuePropName='registrationTime'
                        getValueProps={value => ({ value:registrationTime || value })}
                        getValueFromEvent={(_, value) => {
                            setRegistrationTime([dayjs(value[0]), dayjs(value[1])]);
                            return value;
                        }}
                    >
                        <RangePicker showTime />
                    </Form.Item>
                    <Row justify="end">
                        <Col>
                            <Space>
                                <Button htmlType="button" onClick={handleCancel}>
                                    {intl.formatMessage({
                                        id: 'component.button.cancel',
                                    })}
                                </Button>
                                <Button type="primary" htmlType="submit" loading={confirmLoading}>
                                    {intl.formatMessage({
                                        id: 'component.button.submit',
                                    })}
                                </Button>
                            </Space>
                        </Col>
                    </Row>
                </Form>
            </Modal>
        </>
    )
};
export default CompetitionOperatePanel;